package com.okaysoft.ofb.account

import org.springframework.dao.DataIntegrityViolationException
import grails.converters.JSON

class DepartmentController {

    def sysService

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {

    }

    def listJson() {
        render(sysService.departmentTreeJson(null) as JSON)
    }

    def save() {
        def departmentInstance
        if (params.id) {
            departmentInstance =  Department.get(params.id)
        }
        if (!departmentInstance)  {
            departmentInstance = new Department()
        }
        departmentInstance.properties = params
        if (!departmentInstance.save(flush: true)) {
            def failure = ["status": 0, "msg": message(code: 'default.save.failure.message', default: 'Save failure')] as JSON
            render(failure.toString())
            return
        }
        def succ = ["status": 1, "msg": message(code: 'default.save.success.message', default: 'Save success')] as JSON
        render(succ.toString())
        return
    }

    def show() {
        def departmentInstance = Department.get(params.id)
        if (!departmentInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'department.label', default: 'Department'), params.id])
            redirect(action: "list")
            return
        }

        [departmentInstance: departmentInstance]
    }

    def delete() {
        def departmentInstance = Department.get(params.id)
        if (!departmentInstance) {
            render([status: 0, msg:  message(code: 'default.not.found.message', args: [message(code: 'department.label', default: 'Department'), params.id])] as JSON)
            return
        }

        try {

            sysService.removeDepartment(departmentInstance)
            render([status: 1, msg:  message(code: 'default.deleted.message', args: [message(code: 'department.label', default: 'Department'), params.id])] as JSON)

        }
        catch (DataIntegrityViolationException e) {
            render([status: 0, msg:  message(code: 'default.not.deleted.message', args: [message(code: 'department.label', default: 'Department'), params.id])] as JSON)

        }
    }
}
